#!usr/bin/python
# coding=utf-8
import os, sys, time, shutil
# import os
# import shutil

import datetime, dateutil


def getVersion():
    # f = open("./cmtMedia/build.gradle", "r+")
    # f = open("./123", "r+")
    f = open("./app/build.gradle", "r+")
    for line in f:

        if line.find(" versionNameStr ") > 0:
            versionName = line.split(" ")[-1]
            versionName = versionName.strip()
            print versionName
            return versionName
    return ""


def getDateString():
    timeFilePath = time.strftime("%Y%m%d", time.localtime())
    print timeFilePath
    return timeFilePath


def mkdirs(path):
    # 去除首位空格
    path = path.strip()
    # 去除尾部 \ 符号
    path = path.rstrip("\\")

    # 判断路径是否存在
    # 存在     True
    # 不存在   False
    isExists = os.path.exists(path)

    # 判断结果
    if not isExists:
        # 创建目录操作函数
        os.makedirs(path)
        # 如果不存在则创建目录
        print path + u' 创建成功'
        return True
    else:
        # 如果目录存在则不创建，并提示目录已存在
        print path + u' 目录已存在'
        return False

reload(sys)
sys.setdefaultencoding('utf-8')
print "begin build"
cmdBuild = "gradle clean assembleRelease"
versionName = getVersion()
datePath = getDateString()
# cmdBuild = "echo 123"
os.system(cmdBuild)
# need 1,src_file; 2,
innerPath = "/" + datePath + "/" + versionName + "/"
des = "/Users/chaoranf/Documents/CmtAndroidApks"+innerPath
src = "./exportApks" + innerPath + "CmtMedia_" + versionName + ".apk"
try:
    # shutil.rmtree(des)
    # shutil.copytree(src, des)
    mkdirs(des)
    shutil.copy(src, des)
except Exception, ex:
    print Exception, ":", ex
finally:
    print "echo copy finished"

print "cmtMedia" + versionName + "build finished"
